package net.xdclass.controller;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.service.DomainService;
import net.xdclass.util.JsonData;
import net.xdclass.vo.DomainVO;
import org.assertj.core.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 功能描述
 *
 * @author ASUS
 * @date 2024/07/29  17:32
 */
@RestController
@RequestMapping("/api/domain/v1")
@Slf4j
public class DomainController {
    @Autowired
    private DomainService domainService;

    /**
     * 列举全部可用域名列表
     * @return
     */
    @GetMapping("list")
    public JsonData listAll(){

        List<DomainVO> list = domainService.listAll();

        return JsonData.buildSuccess(list);

    }



    @Autowired
    //注入的是redisTemplateConfiguration里的bean
    private RedisTemplate<Object,Object> redisTemplate;
    @GetMapping("test")
    public JsonData test(@RequestParam("code") String code , @RequestParam("accountNo") Long accountNo){
        //key1是短链码，ARGV[1]是accountNo,ARGV[2]是过期时间
        String script =
                //如果key1不存在
                "if redis.call('EXISTS',KEYS[1])==0 then redis.call('set',KEYS[1],ARGV[1]); redis.call('expire',KEYS[1],ARGV[2]); return 1;" +
                //如果key1=accountno，代表可重入
                " elseif redis.call('get',KEYS[1]) == ARGV[1] then return 2;" +
                " else return 0; end;";
        //result>0加锁成功
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(code), accountNo, 100);
        log.info("result:{}",result);
        return JsonData.buildSuccess(result);

    }




}
